/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package pl.edu.agh.soa.monitoring;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.util.Collection;

import javax.annotation.PostConstruct;
import javax.jbi.component.ComponentContext;
import javax.jbi.management.DeploymentException;
import javax.jbi.messaging.ExchangeStatus;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.NormalizedMessage;
import javax.management.ObjectName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.dom.DOMSource;

import org.apache.log4j.Logger;
import org.apache.servicemix.common.Registry;
import org.apache.servicemix.common.endpoints.ProviderEndpoint;
import org.apache.servicemix.jbi.container.JBIContainer;
import org.apache.servicemix.jbi.framework.ComponentContextImpl;
import org.apache.servicemix.jbi.framework.ServiceAssemblyLifeCycle;
import org.apache.servicemix.jbi.framework.ServiceUnitLifeCycle;
import org.apache.servicemix.jbi.jaxp.StringSource;
import org.apache.servicemix.jbi.messaging.DeliveryChannelImpl;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * @org.apache.xbean.XBean element="listingEndpoint"
 */
public class ListingEndpoint extends ProviderEndpoint implements
		IListerEndpoint {

	private final static Logger logger = Logger
			.getLogger(ListingEndpoint.class);

	private JBIContainer container;

	DocumentBuilder builder;

	public void validate() throws DeploymentException {
	}

	@Override
	public void activate() {
		try {
			super.activate();
			container = getContainer(getContext());
			builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void processInOut(MessageExchange exchange, NormalizedMessage in,
			NormalizedMessage out) throws Exception {
		if (exchange.getStatus() == ExchangeStatus.ACTIVE) {
			logger.info("Service Assemblies:");
			Document document = builder.newDocument();
			Element mainElement = document.createElement("services-semantics");
			Collection<ServiceAssemblyLifeCycle> serviceAssembliesCollection = container
					.getRegistry().getServiceAssemblies();
			for (ServiceAssemblyLifeCycle salc : serviceAssembliesCollection) {
				logger.info("\t" + salc.getName() + " - "
						+ salc.getDescription());
				Element assemblyElement = document
						.createElement("service-assembly");
				Attr attr = document.createAttribute("name");
				attr.setValue(salc.getName());
				assemblyElement.setAttributeNode(attr);
				Element descriptionElement = document
						.createElement("description");
				descriptionElement.setTextContent(salc.getDescription());
				assemblyElement.appendChild(descriptionElement);

				for (ServiceUnitLifeCycle sulc : salc.getDeployedSUs()) {
					logger.info("\t\t" + sulc.getName() + " - "
							+ sulc.getDescription());
					String descriptor = sulc.getDescriptor();

					if (descriptor != null) {
						Document doc = parseSemanticInformationFromDescriptor(descriptor);
						Element unitElement = document
								.createElement("service-unit");
						Attr unitAttr = document.createAttribute("name");
						unitAttr.setValue(sulc.getName());
						unitElement.setAttributeNode(unitAttr);
						Element unitDescriptionElement = document
								.createElement("description");
						unitDescriptionElement.setTextContent(sulc
								.getDescription());
						unitElement.appendChild(unitDescriptionElement);
						Node firstChildNode = doc.getFirstChild();
						if (firstChildNode != null){
							unitElement.appendChild(document.importNode(firstChildNode, true));
						}
						assemblyElement.appendChild(unitElement);
					}
				}
				mainElement.appendChild(assemblyElement);
			}
			document.appendChild(mainElement);
			out.setContent(new DOMSource(document));
		}
	}

	private Document parseSemanticInformationFromDescriptor(String descriptor) {
		Document doc = null;
		try {
			Document document = builder.parse(new InputSource(new StringReader(descriptor)));
			NodeList semanticNodes = document.getElementsByTagName("service-semantic");
			doc = builder.newDocument();
			for(int i = 0 ; i < semanticNodes.getLength() ; i++){
				doc.appendChild(doc.importNode(semanticNodes.item(i),true));
			}
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return doc;
	}

	private JBIContainer getContainer(ComponentContext context) {
		try {
			Field field = context.getClass().getDeclaredField("context");
			field.setAccessible(true);
			context = (ComponentContext) field.get(context);
		} catch (Exception e) {
		}
		try {
			Field field = context.getClass().getDeclaredField("container");
			field.setAccessible(true);
			JBIContainer container = (JBIContainer) field.get(context);
			return container;
		} catch (Exception e) {
			return null;
		}
	}

}
